/**
 * create by young (young2f@outlook.com) on 2019/11/22
 */
'use strict';
const fileUtils = require('./fileUtils');
const fs = require('fs');
const path = require('path');

async function getSmartNodeConfig(app) {
    const path = app.config.rootPath;
    return fileUtils.readFile2json(app.config.sysConfigFile)
        .then(json => {
            if (json === undefined) {
                json = app.config.iiotConfig;
                json.rootPath = path;
                fileUtils.writeFile(app.config.sysConfigFile, json);
            }
            const pkg = getPackageJson();
            const version = pkg.version;
            app.config.version = version;
            app.logger.level = json.logger.level;
            app.iiotConfig = json;
            return json;
        });
}

async function setSmartNodeConfig(app, json) {
    if (json === undefined) return Promise.resolve('ok');
    return fileUtils.writeFile(app.config.sysConfigFile, json);
}


function getPackageJson() {
    const _packageJson = fs.readFileSync(path.resolve(__dirname, '../../package.json'));
    return JSON.parse(_packageJson);
}

function getEggPlugin() {
    const dir = path.resolve(__dirname, '../libs/plugin/');
    let components = [];
    const files = fs.readdirSync(dir);
    files.forEach(function (item, index) {
        let stat = fs.lstatSync(dir + '/' + item);
        if (stat.isDirectory() === true) {
            components.push(item);
        }
    });

    return components;
}

module.exports = {
    getSmartNodeConfig,
    setSmartNodeConfig,
    getPackageJson,
    getEggPlugin,
};
